package cn.lsc.org.service.impl;

import cn.lsc.basic.service.impl.BaseServiceImpl;
import cn.lsc.org.domain.Department;
import cn.lsc.org.mapper.DepartmentMapper;
import cn.lsc.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper mapper;

    @Override
    public void add(Department department) {
        // 返回自增的主键 id
        mapper.save(department);
        // department  页面传的， 有没有dirPath???
        // 1. 没有上级部门    dirPath = /id
       /* if(department.getParent_id()==null){
            Long id = department.getId();
            //  设置dirPath
            department.setDirPath("/"+id);
        }else{   // 2. 有上级部门
            // 通过parent_id 获取上级的dirPath
            Long parent_id = department.getParent_id();
            // 父级部门对象
            Department parentDepartment = mapper.loadById(parent_id);
            // dirPath
            department.setDirPath(parentDepartment.getDirPath()+"/"+department.getId());
        }*/

        // 调用update方法，更新到数据库
        update(department);

    }

    @Override
    public void update(Department department) {
        // 1. 没有上级部门
        if(department.getParent_id()==null){
            Long id = department.getId();
            //  设置dirPath
            department.setDirPath("/"+id);
        }else{   // 2. 有上级部门
            // 通过parent_id 获取上级的dirPath
            Long parent_id = department.getParent_id();
            // 父级部门对象
            Department parentDepartment = mapper.loadById(parent_id);
            // dirPath
            department.setDirPath(parentDepartment.getDirPath()+"/"+department.getId());
        }

        mapper.update(department);

    }

    @Override
    public List<Department> deptTree() {
        // 1. 查询所有
        List<Department> all = mapper.loadAll();

        // 2 .准备一个map
        HashMap<Long, Department> map = new HashMap<>();

        // 3.把所有数据放入map中
        for (Department department : all) {
            map.put(department.getId(),department);
        }

        // 4. 准备一个list，保存处理之后的数据
        List<Department> deptTree = new ArrayList<>();
        for (Department department : all) {
            if(department.getParent_id()==null){ // 顶级部门
                deptTree.add(department);
            }else{
                // 获取parent_id
                Long parent_id = department.getParent_id();
                // 获取上级部门对象
                Department parentDepartment = map.get(parent_id);

                // 把自己放入上级部门的children中
                parentDepartment.getChildren().add(department);
            }
        }

        // 返回部门树
        return deptTree;
    }

}
